package domain.service;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import domain.data.QnAPersistenceManager;
import domain.model.Domain;


public class AgeDomain {
	public AgeDomain(String name_domain)
	{
		String message = null;
		try {
			message = URLEncoder.encode(name_domain, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        try {
        	PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
            URL url = new URL("http://www.seologs.com/dns/domain-check.html");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("query=" + message);
            writer.write("&output=cdt");
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            	 String content = "";
            	 while(1==1)
     			 {
     				 String str = reader.readLine();
     				 if(str==null) break;
     				 content+=str;   				
     			 }
            	 Document doc = Jsoup.parse(content);
            	 String age = doc.select("div[class=KonaBody]").select("p").text();
            	 String[] ageSplit = age.split("(approximately)");
            	 if(ageSplit.length ==2)
            	 {
            		 	@SuppressWarnings("unchecked")
	     				List<Domain> domainList=  (List<Domain>)psm.newQuery(Domain.class,"name == '"+name_domain+"'").execute();
	     				if(domainList.size()>0)
	     				{
	     					Domain domain = domainList.get(0);
	     					
	     					domain.setDomainAge(ageSplit[1].replaceAll("[):]+", ""));
	     					
	     					psm=JDOHelper.getPersistenceManager(domain);
	     					psm.currentTransaction().begin();
	     					psm.makePersistent(domain);
	     					psm.currentTransaction().commit();
	     				} 
            	 }
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

	}
//	public static void main( String args[])
//	{
//		new AgeDomain("google.com");
//	}
}
